import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
  },
  getters: {
    isLogin: state => !!state.token,
    isAdmin: state => state.userInfo.role === 2,
    userId: state => state.userInfo.id,
    username: state => state.userInfo.username,
    nickname: state => state.userInfo.nickname || state.userInfo.username
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      
      // Also store role separately for easier access in navigation guards
      if (userInfo && userInfo.role) {
        localStorage.setItem('role', userInfo.role.toString())
      }
    },
    logout(state) {
      state.token = ''
      state.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('role')
    }
  },
  actions: {
    login({ commit }, { token, userInfo }) {
      commit('setToken', token)
      commit('setUserInfo', userInfo)
    },
    logout({ commit }) {
      commit('logout')
    }
  }
}) 